package com.puzzlebazar.client.util;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class BasicFilter implements KeyPressHandler {

	private final char extraKeys[];
	
	public BasicFilter() {
		extraKeys = null;
	}

	public BasicFilter( final char extraKeys[] ) {
		this.extraKeys = extraKeys;
	}
	
	public void onKeyPress(Widget sender, char keyCode, int modifiers) {

	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		assert( event.getSource() instanceof TextBox );
		TextBox sender = (TextBox)event.getSource();
		char keyCode = event.getCharCode();

		if ( !Character.isDigit(keyCode) && !Character.isLetter(keyCode) 
				&& keyCode != '_'  
				&& (keyCode != (char) KeyCodes.KEY_TAB)
				&& (keyCode != (char) KeyCodes.KEY_BACKSPACE)
				&& (keyCode != (char) KeyCodes.KEY_ENTER) ) {
			// TextBox.cancelKey() suppresses the current keyboard event.
			if( extraKeys != null ) {
				for (int i = 0; i < extraKeys.length; i++) {
					if( keyCode == extraKeys[i] ) return;
				}
			}
			((TextBox)sender).cancelKey();			
		}	}


}
